package com.livegoods.service.impl;

import com.livegoods.commons.pojo.LivegoodsResult;
import com.livegoods.pojo.Item;
import com.livegoods.service.RecommendationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RecommendationServiceImpl implements RecommendationService {

    @Autowired
    private MongoTemplate mongoTemplate;

    //热销商品：按照城市（city）和是否热门（recommendation）搜索，查询四条数据

    @Value("${livegoods.fastdfs.nginx}")
    private String nginx;

    @Override
    public LivegoodsResult findRecommendationProduct(String city) {


        try {

            Criteria criteria1 = Criteria.where("city").is(city);//城市

            Criteria criteria2 = Criteria.where("recommendation").is(true);//热门产品

            Criteria criteria = new Criteria();
            criteria.andOperator(criteria1,criteria2);

            Query query = new Query(criteria);

            query.with(PageRequest.of(0,4));

            List<Item> items = mongoTemplate.find(query, Item.class);

            for (Item item : items) {
                item.setImg(nginx+item.getImg());
            }
            return LivegoodsResult.ok(items);
        } catch (Exception e) {
            e.printStackTrace();
            return LivegoodsResult.error("查询热销商品失败...");
        }
    }
}
